<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use think\db\Expression;
use think\Exception;
use think\Hook;
use think\Model;


class Withdraw extends Model
{

    // 表名
    protected $name = 'xiluedu_withdraw';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'createtime_text',
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /**
     * 获取提现次数
     * @param $where
     */
    public static function withdraw_count($where){
        return static::where($where)->count();
    }

    /**
     * @param $money
     */
    public static function withdraw($money){
        $config = Config::getMyConfig('apply');
        if(!$config || $config['apply_status'] != '1'){
            throw new Exception("提现未开启或未配置");
        }
        if($config['apply_small_money'] > $money){
            throw new Exception("低于最低提现金额");
        }
        if($config['apply_large_money'] < $money){
            throw new Exception("高于最高提现金额");
        }
        $withdraw_count = static::withdraw_count(['createtime'=>['between',[strtotime(date('Y-m-d')), strtotime(date('Y-m-d 23:59:59'))]]]);
        if($config['apply_daily_num'] <=$withdraw_count){
            throw new Exception("达到每天提现次数上限");
        }
        $user = (Auth::instance())->getUser();
        #判断用户余额是否充足
        $account = UserMessageAccount::get(['user_id'=>$user->id]);
        if(!$account || $account->money < $money){
            throw new Exception("余额不足");
        }
        #添加提现记录
        $rate = isset($config['apply_rate']) ? bcdiv($config['apply_rate'],100,2) :0; //手续费率
        $rate_money = bcmul($rate, $money,2);
        $real_money = $money - $rate_money;
        $withdraw = [
            'user_id'   =>  $user->id,
            'money'     =>  $money,
            'real_money'=>  $real_money,
            'rate'      =>  $rate,
            'rate_money'=>  $rate_money,
            'state'     =>  '1'
        ];
        static::startTrans();
        $result = self::create($withdraw);
        $account->money = new Expression("money-".$money);
        $account->save();
        Hook::listen("xiluedu_withdraw_log",$result);
        static::commit();
        return $result;
    }
}
